﻿using System;
using System.Net;
using System.Linq;
using System.Threading.Tasks;

namespace System.Collections.Generic
{
    public static class CommonGenericExtensions
    {
        /// <summary>
        /// Prepends an item to the beginning of an enumeration
        /// </summary>
        /// <typeparam name="T">The type of item in the enumeration</typeparam>
        /// <param name="list">The existing enumeration</param>
        /// <param name="head">The item to return before the enumeration</param>
        /// <returns>An enumerator that returns the head, followed by the rest of the list</returns>
        public static IEnumerable<T> PrependWith<T>(this IEnumerable<T> list, T head)
        {
            yield return head;
            foreach (T item in list)
                yield return item;
        }

        public static IList<T> Cast<T>(this IList self)
        {
            IList<T> tmp = new List<T>();
            foreach (var v in self)
                tmp.Add((T)v);
            return tmp;
        }

        public static void ForEach<T>(this IEnumerable<T> self, Action<T> action)
        {
            if(self.Any())
            foreach (T iter in self)
                action(iter);
        }

        public static T RemoveLast<T>(this IList<T> source)
        {
            T local = source[source.Count - 1];
            source.RemoveAt(source.Count - 1);
            return local;
        }

        /// <summary>
        /// Add a range of items to a collection.
        /// </summary>
        public static ICollection<T> AddRange<T>(this ICollection<T> collection, IEnumerable<T> items)
        {
            if (collection == null) throw new System.ArgumentNullException("collection");
            if (items == null) throw new System.ArgumentNullException("items");

            foreach (var each in items)
                collection.Add(each);

            return collection;
        }
    }
}
